<template>
  <div v-if="show">
    <svg-icon :icon-class="full ? 'exit-fullscreen' : 'fullscreen'" @click="click" />
  </div>
</template>

<script>
import screenfull from 'screenfull'

export default {
  name: 'Screenfull',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      //true是进入全屏，false是退出全屏
      full: false,
    };
  },
  created() {
    //指向问题先保存
    let that = this;
    //这里是监听ESC的
    window.onresize = function () {
      if (!that.checkFull()) {
        // 退出全屏后要执行的动作
        console.log("退出全屏");
        that.full = false;
        that.$store.dispatch('settings/changeSetting', {
          key: 'isFullscreen',
          value: that.full
        })
      }
    };
  },
  mounted() {
    //这里是监听F11案件的
    window.addEventListener("keydown", this.KeyDown, true); // 监听按键事件
  },
  methods: {
    // 进入或者退出全屏
    click() {
      if (this.full) {
        this.exitFullscreen()
      } else {
        this.enter_full_screen()
      }
    },
    //进入全屏模式
    enter_full_screen() {
      this.full = true;
      document.documentElement.webkitRequestFullScreen();
      let screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      this.$store.dispatch('settings/changeSetting', {
        key: 'isFullscreen',
        value: this.full
      })
    },
    //退出全屏模式
    exitFullscreen() {
      this.full = false;
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
      this.$store.dispatch('settings/changeSetting', {
        key: 'isFullscreen',
        value: this.full
      })
    },
    //监听解决F11打开后无法esc退出同时退出全屏的按钮也失效问题。
    KeyDown(event) {
      if (event.keyCode === 122) {
        event.returnValue = false;
        this.enter_full_screen(); //这里方的是触发全屏的方法
      }
    },
    //监听ESC事件，解决点击按钮全屏后按ESC退出再点击按钮不生效问题。
    checkFull() {
      //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
      //火狐浏览器
      var isFull =
        document.mozFullScreen ||
        document.fullScreen ||
        //谷歌浏览器及Webkit内核浏览器
        document.webkitIsFullScreen ||
        document.webkitRequestFullScreen ||
        document.mozRequestFullScreen ||
        document.msFullscreenEnabled;
      if (isFull === undefined) {
        isFull = false;
      }
      return isFull;
    },
  },
}
</script>

<style scoped>
.screenfull-svg {
  display: inline-block;
  cursor: pointer;
  fill: #5a5e66;
  ;
  width: 20px;
  height: 20px;
  vertical-align: 10px;
}
</style>
